<?php

namespace app\index\service;

use app\common\model\Area;
use app\index\dao\AreaDao;
use app\index\model\UM as UM;
use ShidianUtil\Api\Amap\Amap;
use think\exception\ValidateException;

/**
 * Class AreaService
 * @package app\index\service
 */
class AreaService
{
    // dao
    private AreaDao $areaDao;
    private Amap $amap;

    public function __construct(AreaDao $areaDao, Amap $amap)
    {
        $this->areaDao = $areaDao;
        $this->amap = $amap;
    }

    /**
     * 查询
     * @param \app\index\model\UM|null $user
     * @return Area
     */
    public function read(?UM $user, array $params): ?Area
    {
        $lng = $params['lng'] ?? null;
        $lat = $params['lat'] ?? null;

        $adcode = $this->getAdcode($lng, $lat);

        if (!is_string($adcode) || is_blank($adcode)) {
            return null;
        }

        return $this->areaDao->findCityByAdcode($adcode);
    }

    /**
     * 使用经纬度进行逆地理编码获取adcode
     * @param $lng
     * @param $lat
     * @return string
     */
    public function getAdcode($lng, $lat)
    {
        $result = $this->amap->regeo($lng, $lat);

        if (!$result->isSuccess()) {
            throw new ValidateException('获取定位城市失败');
        }

        try {
            $data = $result->getDecodeContents();
            $adcode = $data['regeocode']['addressComponent']['adcode'];
            if (!is_string($adcode)) {
                return null;
            }
            return $adcode;
        } catch (\Exception $exception) {
            throw new ValidateException('获取定位城市失败');
        }

    }

}
